package com.itheima.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author LXX
 */
public class JwtUtils {

    public static final String SUBJECT = "LiXunXun";

    /**
     * 过期时间，毫秒，一天
     */
    public static final long EXPIRE = 1000 * 60 * 60 * 24;

    /**
     * 密钥
     */
    public static final String APPSECRET = "LiXunXun";

    /**
     * 生成jwt
     *
     * @param map 需要生成的token的对象
     * @return 生成的token
     */
    public static String geneJsonWebToken(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        JwtBuilder jwtBuilder = Jwts.builder().setSubject(SUBJECT);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }
        return jwtBuilder.setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
    }



    /**
     * 校验token
     *
     * @param token jwt生成的token
     * @return 返回对象结果集(map类型)
     */
    public static Claims checkJwt(String token) {
        try {
            return Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
        } catch (Exception ignored) {
        }
        return null;
    }

}